import Moment from "moment";
import api from "@/server/userConfig";
/**
 * getXAxis（）方法作用：获取开始日期和结束日期之间（包含开始日期和结束日期）的日期数组，可作为时间轴坐标等
 * @param  filters: {tab:0/1/2, startTime:开始日期, endTime:结束日期}
 * 说明： tab：取值0或1或2，分别表示日、月、年，对应的startTime和endTime的格式分别为'YYYY-MM-DD'、'YYYY-MM'、'YYYY'
 */

function buildDateAxis(parames) {
  let { timeFormat, startTime, endTime } = parames;
  // 计算两个日期之间间隔的天数,月数,年数
  let length = 0; //日期跨度变量

  if (timeFormat == "days") {
    length = Moment(endTime).diff(Moment(startTime), "days");
  } else if (timeFormat == "months") {
    length = Moment(endTime).diff(Moment(startTime), "months");
  } else if (timeFormat == "years") {
    length = Moment(endTime).diff(Moment(startTime), "years");
  }

  let xAxis = new Array(length + 1);

  for (let index = 0; index < xAxis.length; index++) {
    if (timeFormat == "days") {
      xAxis[index] = Moment(startTime)
        .add(index, "days")
        .format("YYYY-MM-DD");
    } else if (timeFormat == "months") {
      xAxis[index] = Moment(startTime)
        .add(index, "months")
        .format("YYYY-MM");
    } else if (timeFormat == "years") {
      xAxis[index] = Moment(startTime)
        .add(index, "years")
        .format("YYYY");
    }
  }

  return xAxis;
}

/**
 * 根据X坐标数组生成对应的Y坐标数组
 * @param  xArr: 上面getXAxis()方法返回的X坐标（时间轴坐标）数组;
 *  list:[{xAxis:"2017-03-01", yAxis:"200"},{xAxis:"2017-03-02", yAxis:"100"},...]  后台返回的坐标点数组，按时间升序排列
 */

function buildYAxis(xArr, list) {
  var len = xArr.length;
  var yAxis = new Array(len);
  var j = 0;
  listLen = list.length;
  for (i in xArr) {
    if (j < listLen && xArr[i] == list[j].xAxis) {
      yAxis[i] = list[j].yAxis;
      j++;
    } else {
      yAxis[i] = 0;
    }
  }

  return yAxis;
}

// 1.用于判断当前变量的值是否为 null 或 undefined 类型。
function isNull(val) {
  return val == undefined || val == null;
}

// 2.用于检查当前的值是否为数字类型。
function isNumber(val) {
  return !isNaN(parseFloat(val)) && isFinite(val);
}

// 3.用于判断参数的值是否是对象
function isObject(val) {
  return val == Object(val);
}

// 4.用于检查当前的值是否为字符串类型。
function isString(val) {
  return typeof val === "string";
}

// 5.用于检查当前的值是否为数组。
function isArray(val) {
  if (Array.isArray) {
    return Array.isArray(val);
  } else {
    return Object.prototype.toString.call(val) == "[object Array]";
  }
}

// 6.用于判断参数的值是否是 Symbol 类型。
function isSymbol(val) {
  return typeof val === "symbol";
}

function buildLinkSelect(lists, lv1key, lv2Key) {
  let lv1 = buildSelectOption(lists, lv1key);
  let lv2 = buildSecondSelectOption(lists, lv1key, lv2Key);
  return {
    lv1,
    lv2
  };
}

function buildSelectOption(lists, lv1key) {
  let _lists = [];
  _lists = lists.map((item, index) => {
    return {
      label: item[lv1key],
      value: item[lv1key]
    };
  });
  return _lists;
}

function buildSecondSelectOption(lists, lv1Key, lv2Key) {
  let listsObj = {};
  lists.forEach((item, index) => {
    listsObj[item[lv1Key]] = item[lv2Key].map((item2, index2) => {
      return {
        label: item2,
        value: item2
      };
    });
  });
  return listsObj;
}

function formatPictureIds(lists) {
  let idLists = [];
  if (lists.length > 0) {
    lists.forEach((item, index) => {
      idLists.push(item.uid);
    });
    return idLists;
  } else {
    return [];
  }
}

function getFirstMenuPath(lists, str = '') {
  if (lists.length > 0 && lists[0].type == 3) {
    str = lists[0].path;
  } else {
    return getFirstMenuPath(lists[0].children, str);
  }
  return str;
}

// 过滤所有的页面路由
function filterRouters(lists, typeValue, arr = []) {
  // lists.forEach((item) => {
  //   let { name, path, type, children } = item;
  //   if (children && children.length > 0) {
  //     return filterRouters(children, typeValue, arr);
  //   } else {
  //     if (type == typeValue) {
  //       arr.push({
  //         path: `/${path}`,
  //         name: `${path}`,
  //         component: () => import(`@/page/${path}/index`),
  //         meta: {
  //           title: name,
  //         },
  //       });
  //     }
  //   }
  // });
  // return arr;

  lists.forEach((item) => {
    let { name, path, type, children } = item;
    if (type == typeValue) {
      arr.push({
        path: `/${path}`,
        name: `${path}`,
        component: () => import(`@/pages/${path}/index`),
        meta: {
          title: name,
        },
      });
    }
    if (children && children.length > 0) {
      return filterRouters(children, typeValue, arr);
    }
  });
  return arr;
}

async function initUserInfo(_this) {
  return {}
  return new Promise(async (resolve, reject) => {
    _this.userName = localStorage.getItem("phone");
    if (!_this.userName) {
      _this.$router.push("/login");
      resolve();
    } else {
      const res = await api.getRoleId({ phoneNumber: _this.userName });
      if (res.MsgCode !== 0) {
        _this.$message.error("获取用户信息失败");
        reject("getRoleId erroe");
      } else {
        // 更新本地存储
        localStorage.setItem("userInfo", JSON.stringify(res.Data));
        let { ID, compid, name, secondDepartment } = res.Data;
        _this.name = name;
        _this.role = ID;
        _this.compId = compid;
        _this.secondDepartment = secondDepartment;
        resolve();
      }
    }
  });
}

// 根据登陆的手机号获取角色id;该方法适用于子组件获取user信息
function getRoleId(_this) {
  _this.userName = localStorage.getItem("phone");
  let userInfoStr = localStorage.getItem("userInfo")
  let userInfo = {
    name:'',
    role:-1,
    compId:-1,
    secondDepartment:''
  };
  if(userInfoStr){
    userInfo = JSON.parse(
      userInfoStr
    );
  }
  let { ID, compid, name, secondDepartment } = userInfo
  _this.name = name;
  _this.role = ID;
  _this.compId = compid;
  _this.secondDepartment = secondDepartment;
}

// 下拉框组件过滤用的函数
function filterSelectLists(input, option) {
  let str = input.replace(/\s*/g, "");
  let name = option.componentOptions.children[0].text;

  if (name == "" || name == undefined || str == "" || str == undefined) {
    return false;
  } else {
    let isMatch = name.indexOf(str) >= 0;
    return isMatch;
  }
}

// 获取区域时间
function getRangeTime(value) {
  // 0.自定义
  // 10.本周 11.上一周 12.下一周 13.过去7天 14.未来7天
  // 20.本月 21.上个月 22.下个月 23.过去30天 15.未来30天
  // 30.本季度 31.上个季度 32.下个季度
  // 40.本年 31.上一年 32.下一年
  switch (value) {
    case 0:
      return [
        moment()
          .quarter(moment().quarter())
          .startOf("quarter"),
        moment()
          .quarter(moment().quarter())
          .endOf("quarter")
      ];
    case 1:
      return [
        moment()
          .quarter(moment().quarter() - 1)
          .startOf("quarter"),
        moment()
          .quarter(moment().quarter() - 1)
          .endOf("quarter")
      ];
    case 2:
      return [
        moment()
          .year(moment().year())
          .startOf("year"),
        moment()
          .year(moment().year())
          .endOf("year")
      ];
    case 3:
      return [
        moment()
          .year(moment().year() - 1)
          .startOf("year"),
        moment()
          .year(moment().year() - 1)
          .endOf("year")
      ];
    case 4:
      return [moment(), moment()];
    default:
      break;
  }
}

// table过滤不想显示的列
function filterTableColumns(columns, filterLists) {
  let _lists = [];
  columns.forEach((item, index) => {
    if (!filterLists.includes(item.dataIndex)) {
      _lists.push(item);
    }
  });
  return _lists;
}

// 深度复制对象
function cloneObject(o){
  var s = {};
  for (var k in o) {
    s[k] = typeof o[k] === "object" ? clone(o[k]) : o[k];
  }
  return s;
}

// 深度复制数组
function cloneObject(arr){
  let _arr = [];
  return _arr.concat(arr1);
}

// 通过不同的字段名,获取不同的下拉框
function buildLists(lists, labelKey, valueKey) {
  return lists.map(item => {
    let newObj = {
      label: item[labelKey],
      value: item[valueKey]
    };
    
    for (const key in item) {
      if (Object.hasOwnProperty.call(item, key)) {
        newObj[key] = item[key];
      }
    }

    return newObj;
  });
}

export {
  buildDateAxis,
  buildLinkSelect,
  initUserInfo,
  getRoleId,
  isNull,
  isNumber,
  isObject,
  isString,
  isArray,
  isSymbol,
  formatPictureIds,
  filterSelectLists,
  getRangeTime,
  filterTableColumns,
  getFirstMenuPath,
  filterRouters
};
